<?php
class ScoreAction extends IntesysAction {
	//插入评价分数并检测是否加分
	public function insert(){
        if(IS_POST){
			$taskCount=count($_POST['score']);
            $_POST['score']=serialize($_POST['score']);
            $_POST['member']=serialize($_POST['member']);
			$_POST['member_id']=session(C('USER_AUTH_KEY'));
			$_POST['datetime']=time();
			
			if ($this->dao->create($data)) {
            	$this->dao->add();
			}
			//将所有的分数相加
			$scoreCount=$this->dao->where(['task_id'=>$_POST['task_id']])->count();
			if($taskCount==$scoreCount){
				$scoreList=$this->dao->where(['task_id'=>$_POST['task_id']])->select();
				$taskList=[];
				$memberList=[];
				foreach($scoreList as $vo){
					$score=unserialize($vo['score']);
					$member=unserialize($vo['member']);
					
					foreach($score as $k => $v){
						$taskList[$k]=isset($taskList[$k])?$taskList[$k]+$v:$v;
						$memberList[$k]=$member[$k];
					}
				}
				//更改任务状态 和 加分(包括另外加的分)
				$even=D('Event');
				$task=new Task();
				$type='Binte';
				import("@.ORG.Integrals.".$type);
				$class=new $type(session(C('USER_AUTH_KEY')));
				foreach($taskList as $k=>$v){
					$inte=round($v/$scoreCount);
					$otherInte=$even->where(['task_id'=>$k,'mission_id'=>0])->getField('member_id,integralnumber');
					if($otherInte){
						foreach($otherInte as $ke=>$va){
							$va=$inte>$va?$va:$inte;
							$inte=$inte-$va;
							$class->giveIntegralMore($va,0,$ke,'',1,time(),__SITEID__);
						}
					}
					$taskstatu=$task->changeStatus(5,$k);	
					$intestatu=$class->giveIntegralMore($inte,0,$member[$k],'',1,time(),__SITEID__);
					if(!$taskstatu&&!$intestatu){$this->error($task->getError());}
				}
				$this->success('操作成功！');
			}
        }
	}
	public function update(){
		if($this->_get('id')){
            $_POST['id']=$_GET['id'];
			$_POST['time']=strtotime($_POST['date']);
			$result=$this->task->update();
			if(!$result){
				die(json_encode(array('statu'=>1)));
			}else{
				die(json_encode(array('statu'=>0,'info'=>$this->task->getError())));
			};
		}
	}
	public function delete(){
		if(!$this->_get('id')){return $this->error('失败');}
		if(!$this->task->delete($_GET['id'])){
			$this->error($this->task->getError());
		}else{
			$this->success('删除成功');
		};
	}
}